package booksManagement;

import java.util.List;
import exceptions.*;
import booksManagement.Copy;
import jpaUtils.JPAUtil;
import javax.persistence.EntityManager;

/**
 * 
 * @author GPIRAUX
 * 10/05/2012
 *
 */
public class CopyDAO
{
	public boolean isEmpty(){
		EntityManager entityManager=JPAUtil.getEntityManager();
		if (entityManager.createNamedQuery("findAllCopies").getResultList().isEmpty())
			return true;
		else
			return false;	
	}





	/**
	 */
	@SuppressWarnings("unchecked")
	public List<Copy> getContent(){
		EntityManager entityManager=JPAUtil.getEntityManager();
		return ((List<Copy>)entityManager.createNamedQuery("findAllCopies").getResultList());
	}






	public boolean add(Copy copy){
			EntityManager entityManager=JPAUtil.getEntityManager();
	try{
				entityManager.persist(copy);
			} catch (Exception e) {
				System.err.println("Problem when saving");
				e.printStackTrace();
				return false;
			}
			return true;
		}







		@Override
		@SuppressWarnings("unchecked")
		public String toString(){
			EntityManager entityManager=JPAUtil.getEntityManager();
			String result="";
			List<Copy> theCopies = (List<Copy>) entityManager.createNamedQuery("findAllCopies").getResultList();
			for (Copy c : theCopies)
				result += c.toString()+ "\n";
					return result;
		}







		/**
		 */
		public Copy get(long copyId) throws BookExistsException {
			EntityManager entityManager=JPAUtil.getEntityManager();
			Copy c = (Copy) entityManager.find(Copy.class, copyId);
			if (c ==null) throw new BookExistsException();
			else return c;
		}






		/**
		 */
		public long size(){
			EntityManager entityManager=JPAUtil.getEntityManager();
			return (entityManager.createNamedQuery("findAllCopiess").getResultList().size());
		}






		/**
		 */
		public boolean remove(Copy copy) throws BookExistsException {
			EntityManager entityManager=JPAUtil.getEntityManager();
			if (copy == null) 
				throw new BookExistsException(); 
			else 
				try{
					entityManager.remove(copy);
				} catch (Exception pe) {
					System.err.println("problem when deleting an entity ");
					pe.printStackTrace();
					return false;
				}
			return true;	
		}





			
			/**
			 */
			public boolean contains(Copy copy) throws BookExistsException {
				EntityManager entityManager=JPAUtil.getEntityManager();
				if (copy == null) throw new BookExistsException();
				Copy c = (Copy) entityManager.find(Copy.class, copy.getNumber());
				if (c ==null) return false;
				else return c.equals(copy);	
					
			}


}

